package rpc

import (
	"crypto/sha1"
	"fmt"
	"golang.org/x/crypto/pbkdf2"
	"log"
	"p2pvpn/kcp"
)

type Server struct {
	listener    *kcp.Listener
	newConnChan <-chan *kcp.UDPSession
}

func StartServer(port int, pass string, salt string) {
	udpSessionsChan := make(chan *kcp.UDPSession, 10)
	key := pbkdf2.Key([]byte(pass), []byte(salt), 1024, 32, sha1.New)
	block, _ := kcp.NewAESBlockCrypt(key)
	if listener, err := kcp.ListenWithOptions(fmt.Sprintf("0.0.0.0:%d", port), block, 10, 3); err == nil {
		go monitorListener(listener, udpSessionsChan)
	} else {
		log.Fatal(err)
		panic(err)
	}
}

func monitorListener(listener *kcp.Listener, udpSessionsChan chan *kcp.UDPSession) {
	for {
		s, err := listener.AcceptKCP()
		if err != nil {
			log.Fatal(err)
		}
		udpSessionsChan <- s
	}
}
